#include "detectwords.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QFile>
#include <QCoreApplication>
#include <QEventLoop>
#include <QApplication>
#include <QScreen>
#include <QRegularExpression>

DetectWords::DetectWords(): QObject()
{
    manager = new QNetworkAccessManager(this);
    client_id = "r25dloq77gfhySPJdS5kloga";
    client_secret = "aeTMteRrReyH2Ks4eNxK7CWprHFlo2Q5";
}

QString DetectWords::getAccessToken()
{
    QString accessToken = "";
    QString requestUrl="https://aip.baidubce.com/oauth/2.0/token";
    QString requestData = "grant_type=client_credentials&client_id="+client_id+"&client_secret="+client_secret;

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(requestUrl));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
    requestInfo.setRawHeader("Accept", "application/json");
    QNetworkReply *reply = manager->post(requestInfo, requestData.toUtf8());

    QEventLoop temp_loop;
    QObject::connect(reply, &QNetworkReply::finished, &temp_loop, &QEventLoop::quit);
    temp_loop.exec();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray responseData = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObj = jsonDoc.object();
        if(jsonObj.contains("access_token"))
        {
            accessToken = jsonObj.value("access_token").toString();
        }
    }
    else
    {
        qDebug() << reply->error();
    }
    reply->deleteLater();
    return accessToken;
}

QJsonArray DetectWords::ocrAccurateBasic(QString accessToken, QRect rect)
{
    QJsonArray result = QJsonArray();

    QScreen *screen = QApplication::primaryScreen();
    QPixmap pixmap = screen->grabWindow(0, rect.x(),rect.y(),rect.width(),rect.height());

    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer, "PNG");
    QString base64Image = ba.toBase64();
    QString imageUrl = QUrl::toPercentEncoding(base64Image);

    QString requestUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic";
    QString requestData = "access_token=" + accessToken + "&image=" + imageUrl + "&detect_direction=false&vertexes_location=false&paragraph=false&probability=false&char_probability=false&multidirectional_recognize=false";

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(requestUrl));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    requestInfo.setRawHeader("Accept", "application/json");
    QNetworkReply *reply = manager->post(requestInfo, requestData.toUtf8());

    QEventLoop temp_loop;
    QObject::connect(reply, SIGNAL(finished()), &temp_loop, SLOT(quit()));
    temp_loop.exec();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray responseData = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObj = jsonDoc.object();
        QJsonValue resultValue = jsonObj.value("words_result");

        if (resultValue.isArray())
        {
            result = resultValue.toArray();
        }
    }
    reply->deleteLater();
    return result;
}

QJsonArray DetectWords::ocrAccurate(QString accessToken, QRect rect)
{
    QJsonArray result = QJsonArray();

    QScreen *screen = QApplication::primaryScreen();
    QPixmap pixmap = screen->grabWindow(0, rect.x(),rect.y(),rect.width(),rect.height());

    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    pixmap.save(&buffer, "PNG");
    QString base64Image = ba.toBase64();
    QString imageUrl = QUrl::toPercentEncoding(base64Image);

    QString requestUrl = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate";
    QString requestData = "access_token=" + accessToken + "&image=" + imageUrl + "&detect_direction=false&vertexes_location=false&paragraph=false&probability=false&char_probability=false&multidirectional_recognize=false";

    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(requestUrl));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    requestInfo.setRawHeader("Accept", "application/json");
    QNetworkReply *reply = manager->post(requestInfo, requestData.toUtf8());

    QEventLoop temp_loop;
    QObject::connect(reply, SIGNAL(finished()), &temp_loop, SLOT(quit()));
    temp_loop.exec();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray responseData = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObj = jsonDoc.object();
        QJsonValue resultValue = jsonObj.value("words_result");

        if (resultValue.isArray())
        {
            result = resultValue.toArray();
        }
    }
    reply->deleteLater();
    return result;
}

QJsonObject DetectWords::queryWithJx3Api(QString subject)
{
    QJsonObject result;
    options.clear();
    qDebug() << subject;
    QString requestUrl="https://www.jx3api.com/data/exam/answer";
    QJsonObject requestData;
    requestData["subject"] = subject;
    requestData["limit"] = 1;
    QByteArray postDataByteArray = QJsonDocument(requestData).toJson();
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(requestUrl));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=utf-8"));

    QNetworkReply *reply = manager->post(requestInfo, postDataByteArray);

    QEventLoop temp_loop;
    QObject::connect(reply, SIGNAL(finished()), &temp_loop, SLOT(quit()));
    temp_loop.exec();

    if(reply->error() == QNetworkReply::NoError)
    {
        QByteArray responseData = reply->readAll();

        QJsonDocument jsonDoc = QJsonDocument::fromJson(responseData);
        QJsonObject jsonObj = jsonDoc.object();
        int code = jsonObj.value("code").toInt();

        if (code == 200)
        {
            QJsonValue resultValue = jsonObj.value("data");
            QJsonArray resultArray = resultValue.toArray();
            result = resultArray.first().toObject();
            qDebug() << "question: " << result.value("question").toString();
            qDebug() << "answer: " << result.value("answer").toString();
        }
    }
    reply->deleteLater();
    return result;
}
